package com.example.demo.task.notify;

import javax.sound.sampled.*;
import java.io.File;

import lombok.extern.slf4j.Slf4j;

/**
 * @author jiangjinwu
 * @version 1.0
 * @since 2025/10/10 1:45
 */

@Slf4j

public class UniversalAudioPlayer {
  public static void play(String filePath) {
    try {
      File audioFile = new File(filePath);
      AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);

      // 获取支持的音频格式
      AudioFormat format = audioStream.getFormat();
      DataLine.Info info = new DataLine.Info(Clip.class, format);

      Clip clip = (Clip) AudioSystem.getLine(info);
      clip.open(audioStream);
      clip.start();

      // 等待播放完成
      while (clip.isRunning()) {
        Thread.sleep(100);
      }

      clip.close();
      audioStream.close();

    } catch (Exception e) {
      System.err.println("无法播放音频: " + e.getMessage());
      e.printStackTrace();
    }
  }
  public static void main(String[] args) {
    // 支持 MP3 / WAV / OGG / FLAC
    playPcm("D:\\快速胜利音效.mp3");
//    play("D:/music/test.wav");
//    play("D:/music/test.ogg");
//    play("D:/music/test.flac");
  }

  public static void playPcm(String filePath) {
    try {
      File audioFile = new File(filePath);
      AudioInputStream in = AudioSystem.getAudioInputStream(audioFile);

      // 获取音频格式
      AudioFormat baseFormat = in.getFormat();

      // 定义目标 PCM 格式
      AudioFormat decodedFormat = new AudioFormat(
          AudioFormat.Encoding.PCM_SIGNED,
          baseFormat.getSampleRate(),
          16,
          baseFormat.getChannels(),
          baseFormat.getChannels() * 2,
          baseFormat.getSampleRate(),
          false
      );

      // 转换为 PCM 格式
      AudioInputStream decodedInput = AudioSystem.getAudioInputStream(decodedFormat, in);

      // 获取数据行并播放
      DataLine.Info info = new DataLine.Info(SourceDataLine.class, decodedFormat);
      SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);

      if (line != null) {
        line.open(decodedFormat);
        line.start();

        byte[] buffer = new byte[4096];
        int nBytesRead;
        while ((nBytesRead = decodedInput.read(buffer, 0, buffer.length)) != -1) {
          line.write(buffer, 0, nBytesRead);
        }

        // 等待播放结束
        line.drain();
        line.stop();
        line.close();
        decodedInput.close();
      }

    } catch (Exception e) {
      System.err.println("无法播放音频: " + e.getMessage());
      e.printStackTrace();
    }
  }
}
